package com.demo.service_admin.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.demo.dao_admin.ArticleDAO;
import com.demo.entity.Article;
import com.demo.entity.Article;
import com.demo.service_admin.ArticleService;

@Service("adminArticleService")
@Transactional
public class ArticleServiceImpl implements ArticleService {

	@Resource(name = "adminArticleDAO")
	ArticleDAO articleDAO;

	@Override
	public Article findById(Integer id) {
		Article article = articleDAO.findById(id).get();
		return article;
	}

	@Override
	public Page<Article> findAll(Article article, Pageable pageable) {
		Specification<Article> spec = new Specification<Article>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if(StringUtils.isNotEmpty(article.getTitle())) {
					Predicate predicate = cb.like(root.get("title").as(String.class), "%"+article.getTitle()+"%");
					predicates.add(predicate);
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
		Page<Article> list = articleDAO.findAll(spec, pageable);
		return list;
	}

	@Override
	public int batchDelete(Integer[] ids) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Article save(Article article) {
		return articleDAO.saveAndFlush(article);
	}

	public int isShow(Integer id, String isShow) {
		return articleDAO.isShow(id, isShow);
	}
	
	
}